package utils

import (
	"github.com/astaxie/beego"
	"github.com/ylywyn/jpush-api-go-client"
)

type JpushClient struct {
	Platform jpushclient.Platform // 推送平台
	Audience jpushclient.Audience // 推送目标
	Notice   jpushclient.Notice   // 推送通知
	Message  jpushclient.Message  // 推送消息
}

func NewJpush() *JpushClient {
	return &JpushClient{}
}

//SetTag 设置推送tag
func (j *JpushClient) SetTag(tags []string) *JpushClient {
	j.Audience.SetTag(tags)
	return j
}

//SetAlias 设置推送别名
func (j *JpushClient) SetAlias(alias string) *JpushClient {
	j.Audience.SetAlias([]string{alias})
	return j
}

//SetID 设置推送id
func (j *JpushClient) SetID(id string) *JpushClient {
	j.Audience.SetID([]string{id})
	return j
}

// 设置通知
func (j *JpushClient) SetAlert(alter string) *JpushClient {
	j.Notice.SetAlert(alter)
	return j
}

// 设置android通知
func (j *JpushClient) SetAndroidNotice(alter string) *JpushClient {
	j.Notice.SetAndroidNotice(&jpushclient.AndroidNotice{Alert: alter})
	return j
}

// 设置ios通知
func (j *JpushClient) SetIOSNotice(alter string) *JpushClient {
	j.Notice.SetIOSNotice(&jpushclient.IOSNotice{Alert: alter})
	return j
}

func (j *JpushClient) SetMessage(title, content string) *JpushClient {
	j.Message.Title = title
	j.Message.Content = content
	return j
}

func (j *JpushClient) SetTitle(title string) *JpushClient {
	j.Message.Title = title
	return j
}

func (j *JpushClient) SetContent(content string) *JpushClient {
	j.Message.Content = content
	return j
}

func (j *JpushClient) AddExtras(key string, value interface{}) *JpushClient {
	if j.Message.Extras == nil {
		j.Message.Extras = make(map[string]interface{})
	}
	j.Message.Extras[key] = value
	return j
}

func (j *JpushClient) Jump(url string) *JpushClient {
	if j.Message.Extras == nil {
		j.Message.Extras = make(map[string]interface{})
	}
	j.Message.Extras["jump"] = url
	return j
}

func (j *JpushClient) Send() error {
	payload := jpushclient.NewPushPayLoad()

	// 添加推送平台
	j.Platform.AddAndrid()
	j.Platform.AddIOS()

	payload.SetPlatform(&j.Platform)
	payload.SetNotice(&j.Notice)
	payload.SetAudience(&j.Audience)
	payload.SetMessage(&j.Message)

	bytes, err := payload.ToBytes()
	if err != nil {
		return err
	}

	client := jpushclient.NewPushClient(
		beego.AppConfig.DefaultString("jpush_master_secret", "27e20a3d67ec96795fa17f2a"),
		beego.AppConfig.DefaultString("jpush_app_key", "8a0d6aa996173caaed3e4df3"),
	)

	_, err = client.Send(bytes)
	if err != nil {
		return err
	}

	return nil
}